package com.rfid.afd.model;

import com.rfid.afd.activity.listener.ModelListener;
import com.rfid.config.ConfigManager;
import com.rfid.db.bean.Rfid;
import com.rfid.jni.RfidDecoder;
import com.rfid.util.LogUtils;
import com.rfid.util.RfidManager;
import com.rfid.util.RfidUitl;
import com.rfid.util.Util;

import java.util.List;

public abstract class BaseModel implements RfidManager.RfidListener{

    protected ModelListener mRfidListener;
    protected RfidDecoder mRfidDecoder;
    public BaseModel() {
        mRfidDecoder = new RfidDecoder();
    }

    public void startScan() {
        RfidManager.getInstance().start();
    }

    public void stopScan() {
        RfidManager.getInstance().stop();
    }

    boolean hasShelf = true;
    @Override
    public void onRfid(String rfid) {
        if(hasShelf) {
            if(mRfidListener != null) {
                mRfidListener.onRfid(rfid);
            }
        } else {
            String level = RfidUitl.decodeLevelEpc(rfid);
            if(RfidUitl.isLevelBarcode(level)) {
                level = level.replace(",","");
                if(mRfidListener != null) {
                    hasShelf = true;
                    mRfidListener.onShelf(level);
                }
            }
        }
    }

    public void setDisableShelf(boolean shelf) {
        hasShelf = shelf;
    }

    private boolean isShelf(String rfid) {
        boolean isShelf = false;
        try {
            String hex = rfid.substring(4 * 2, rfid.length());
            byte data[] = Util.hexStr2bytes(hex);
            int r = 0;
            if (hex.length() > 16) {
                r = mRfidDecoder.iRFID_Decode128bit(data);
            } else {
                r = mRfidDecoder.iRFID_Decode96bit(data);
            }
            String barcode = new String(data).trim();
            if(barcode.length() == ConfigManager.getInstance().getConfig().getShelfLabLen()) {
                isShelf = true;
                if(mRfidListener != null) {
                    mRfidListener.onShelf(barcode);
                }
            }
            if (r > 0) {
            } else {
                LogUtils.d("decode fail rfid = " + rfid + ",r = " + r);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isShelf;
    }

    public void setRfidListener(ModelListener listener) {
        if(listener == null) {
            RfidManager.getInstance().setRfidListener(null);
            mRfidListener = null;
            return;
        }
        mRfidListener = listener;
        RfidManager.getInstance().setRfidListener(this);
    }

}
